import axios from "axios";
import { useStore } from '@/store/index';
import { storeToRefs } from "pinia";

import { showToast } from 'vant';
let instance = axios.create({
  timeout: 30000,
  baseURL: import.meta.env.VITE_APP_API
});


instance.interceptors.request.use(
  (config) => {
    const store = useStore();
    const { accessToken, userInfo } = storeToRefs(store)
    console.log(accessToken, userInfo, '请求')
    var token = userInfo.value.token || accessToken.value
    console.log(token, '请求所用的token')
    if (token) {
      config.headers["token"] = token;
      config.headers["openId"] = userInfo.value.openId
    }

    return config;
  },
  error => {
    console.log(error, "请求拦截error")
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    const res = response.data;
    const store = useStore();
    // if (res.code !== 200) {
    //   showToast({
    //     message: `${res.msg}`,
    //     position: "bottom",
    //     duration: 2000
    //   });
    // }
    if (res.code === 9999) {
      // 身份过期,请重新登录
      showToast('登录失效,请刷新页面重试')
      store.setLoginStatus(0)
      store.setAccessToken('')
      // await store.dispatch('setRefreshToken', refresh_token)
      store.setUserInfo({})
      window.location.reload()
      // const timer = setTimeout(() => {
      //     clearInterval(timer);
      //     Toast.clear();
      // }, 3000);

      return
    }
    return res;
  },
  error => {
    console.log(error, "响应拦截   error")

    if (error && error.response) {
      switch (error.response.status) {
        case 500:
          showToast({
            message: `服务器内部错误`,
            position: "bottom"
          });
          break;
      }
    }
    return Promise.reject(error);
  }
);
class Http {
  static async get(url, params) {
    return await instance.get(url, { params });
  }
  static async post(url, params) {
    return await instance.post(url, params);
  }
}

export default Http;
